//
//  HQYSearchViewController.m
//  Go!
//
//  Created by rimi on 16/7/12.
//  Copyright © 2016年 黄秋燕. All rights reserved.
//

#import "HQYSearchViewController.h"
#import "HQYSearchModel.h"
#import "HQYSearchDetailViewController.h"

#define Cell_RowHeight Size_H(50)
@interface HQYSearchViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITextField *searchTextField; /**< 搜索文本框 */
@property (nonatomic, strong) UIButton *searchButton; /**< 搜索按钮 */
@property (nonatomic, strong) UITableView *searchResultTable; /**< 查询结果列表 */
@property (nonatomic, assign) CGFloat tableViewHeight; /**< 表格的高度 */

@property (nonatomic, strong) HQYSearchModel *model; /**< 查询模型 */
@property (nonatomic, strong) NSArray *tableModelArray; /**< 列表数据数组 */
@end

@implementation HQYSearchViewController
- (void)dealloc {
    // 移除观察者
    [self.model removeObserver:self forKeyPath:@"response"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self initializeNavTextField];
    
    // 搜索按钮
    _searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _searchButton.bounds = CGRectMake(0, 0, Size_W(60), Size_H(30));
    _searchButton.center = CGPointMake(CGRectGetMaxX(self.searchTextField.frame) + Size_W(40), (CGRectGetMaxY(self.navigationController.navigationBar.frame) - Size_H(25)) *0.5);
    _searchButton.backgroundColor = ColorWith(246, 83, 53);
    _searchButton.layer.cornerRadius = 8;
    _searchButton.titleLabel.font = [UIFont systemFontOfSize:Font(15)];
    [_searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [_searchButton addTarget:self action:@selector(clickedSearchBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:_searchButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableModelArray = @[];
    [self.model addObserver:self forKeyPath:@"response" options:NSKeyValueObservingOptionNew context:nil];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}

#pragma mark --返回按钮监听
- (void)clickBackItem {
    [super clickBackItem];
    
    [_searchTextField removeFromSuperview];
    [_searchButton removeFromSuperview];
}

#pragma mark --搜索按钮监听
- (void)clickedSearchBtn {
    self.tableModelArray = @[];
    [self.model getListWithKeyWords:self.searchTextField.text];
    
    // 添加表格
    [self.view addSubview:self.searchResultTable];
}

// 监听到状态变化会执行该方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"response"]) {
        self.tableModelArray = [self.model getDataArray];
        [self.searchResultTable reloadData];
    }
}

#pragma mark - initialize
// 搜索框
- (void)initializeNavTextField {
    UITextField *textField = [[UITextField alloc] init];
    textField.frame = CGRectMake(0, 0, Size_W(240), Size_H(30));
    textField.center = CGPointMake(self.navigationController.navigationBar.center.x, (CGRectGetMaxY(self.navigationController.navigationBar.frame) - Size_H(25)) *0.5);
    textField.tintColor = ColorWith(237, 78, 48); // 修改光标颜色
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.layer.borderColor     = [UIColor lightGrayColor].CGColor;
    textField.layer.borderWidth     = 1;
    // 提示文本字体、颜色、大小
    textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索商家、分类、地点" attributes:@{NSForegroundColorAttributeName:[UIColor grayColor], NSFontAttributeName:[UIFont systemFontOfSize:Font(14)]}];
    
    // 占位图片
    textField.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *imgView   = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 8, 8)];
    imgView.image          = [UIImage imageNamed:@""];
    imgView.contentMode    = UIViewContentModeScaleToFill;
    textField.leftView     = imgView;
    
    _searchTextField = textField;
    [self.navigationController.navigationBar addSubview:_searchTextField];
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>
//返回当前每组有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = self.tableModelArray.count;
    // 动态更新表格的大小
    _tableViewHeight = Cell_RowHeight * count;
    
    // 表格的大小是否超过屏幕大小
    if (_tableViewHeight > ScreenH- 64 - 49) {
        _searchResultTable.frame = CGRectMake(0, 64, ScreenW, ScreenH- 64 - 49);
        _searchResultTable.scrollEnabled = YES;
    }
    else {
        _searchResultTable.frame = CGRectMake(0, 64, ScreenW, _tableViewHeight);
        _searchResultTable.scrollEnabled = NO;
    }
    return count;
}

//返回每一行的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"myCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }

    cell.imageView.image = IMAGE(@"搜索-灰");
    cell.textLabel.text = self.tableModelArray[indexPath.row][@"shopName"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@个结果", self.tableModelArray[indexPath.row][@"dealNum"]];

    return cell;
}

//点击时的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HQYSearchDetailViewController *deatilVC = [[HQYSearchDetailViewController alloc] init];
    deatilVC.tableModelArray = self.tableModelArray[indexPath.row];
    [self.navigationController pushViewController:deatilVC animated:YES];
    [_searchTextField removeFromSuperview];
    [_searchButton removeFromSuperview];
}

#pragma mark - Getter
- (UITableView *)searchResultTable {
    if (!_searchResultTable) {
        _searchResultTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenW, _tableViewHeight) style:UITableViewStylePlain];
        _searchResultTable.delegate = self;
        _searchResultTable.dataSource = self;
        _searchResultTable.rowHeight = Cell_RowHeight;
    }
    return _searchResultTable;
}

- (HQYSearchModel *)model {
    if (!_model) {
        _model = [[HQYSearchModel alloc] init];
    }
    return _model;
}

@end
